<?php
/**
 * php GEM Project
 * 
 * LICENSE
 * 
 * PHP System Architecture Enabling Rapid Application Deployment and Scalability
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * @copyright Copyright (C) 2010 Zeletron LLC (http://zeletron.com)
 * @license http://gem.zeletron.com/license
 */

/**
 * GEM/Validate/Confirm.php
 * 
 * @author David Joly
 * @category GEM
 * @package GEM_Validate
 */

class GEM_Validate_Confirm extends Zend_Validate_Abstract 
{ 
	/**
	 * Validation failure message keys.
	 */
	const NOT_MATCH = 'notMatch';
	const NO_CONTEXT = 'noContext';
	const MISSING_FIELD = 'missingField'; 
    
	/**
     * Validation failure message template definition
     *
     * @var array
     */
	protected $_messageTemplates = array(
		self::NOT_MATCH 	=> 'Fields must match.',
		self::NO_CONTEXT 	=> 'Context not found. Cannot validate.',
		self::MISSING_FIELD => 'Missing context field. Cannot validate.'	
	); 
    
	/**
	 * The field to be validated against.
	 * 
	 * @var string
	 */
	protected $_field;
	
	/**
	 * Accepts a field value. This value is the index key
	 * used to locate the value in the context array. When
	 * attaching to a form field, pass the field's element
	 * name in the options array.
	 * 
	 * @param string $field 
	 * @return void
	 */
	public function __construct($field){
		$this->_field = $field;
	}
    /**
     * This function will return false if the value does not
     * match the confirmation field value.
     * 
     * @param $value
     * @param $context 
     * @return bool
     */
	public function isValid($value, $context = null) 
	{ 
		$value = (string) $value; 
        $this->_setValue($value);
        if(!is_array($context)){
        	$this->_error(self::NO_CONTEXT);
        	return false;
        }
        if(!array_key_exists($this->_field,$context)){
        	$this->_error(self::MISSING_FIELD);
        	return false;
        }             
        if($value != $context[$this->_field]){
        	$this->_error(self::NOT_MATCH);
        	return false;
        }
        return true;
	} 
} 